<template>
  <div>
    <el-dialog title="普通权限分配" :visible.sync="normalPermissionVisible" :before-close="close" width="600px">
      <el-form v-loading="loading" ref="form" label-width="80px">
        <el-form-item label="普通权限">
          <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 10px 0;"></div>
          <div v-for="(item, group_index) in normalPermission" :label="item" :key="group_index">
            <span style="color:red">{{item.label}}</span>
            <el-checkbox v-model="checkList" v-for="a in item.children" :label="a.value" :key="a.value">{{a.label}}</el-checkbox>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateNormalPermissions()">确认</el-button>
        <el-button @click="close">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: ["normalPermissionVisible", "roleid"], //接受父组件的值
  data() {
    return {
      normalPermission: [],
      loading: true,
      checkAll: false,
      checkList: []
    };
  },

  created() {
    this.getNormalPermission();
    this.getNormalPermissionByRole();
  },

  methods: {
    //加载所有普通权限
    getNormalPermission: function() {
      this.$api.get("/api/Role/LoadNormalTree", null).then(rsp => {
        if (rsp != false) {
          this.loading = false;
          this.normalPermission = rsp.data;
        }
      });
    },

    //加载某个角色的普通权限
    getNormalPermissionByRole: function() {
      this.$api
        .get("/api/Role/getNormalPermissionByRoleId", { roleId: this.roleid })
        .then(rsp => {
          if (rsp != false) {
            this.loading = false;
            this.checkList = rsp.data;
          }
        });
    },

    //全选
    handleCheckAllChange(val) {
      if (val) {
        let _all = [];
        this.normalPermission.forEach(v => {
          v.children.forEach(p => {
            _all.push(p.value);
          });
        });
        this.checkList = _all;
      } else {
        this.checkList = [];
      }
    },

    updateNormalPermissions() {
      let permissions= this.checkList!=null?this.checkList.join(","):"";
      this.$api
        .post("/api/Role/updateNormalPermissions", {
          roleId: this.roleid,
          permissions:permissions
        })
        .then(rsp => {
          if (rsp != false) {
            this.close();
          }
        });
    },
    close() {
      this.$emit("closeNormal");
    }
  }
};
</script>



